<template>
	<view class="container">
			<view class="mask" v-if='showMask'>
				<view class="tips_join" style="position:relative">
					<view class="" style="display: flex;align-items: center;">
						<!-- <image src="../../static/images/tip.png" style="width:40rpx;height:40rpx" mode=""></image> -->
						<text @click='back' style="font-size: 16px;font-weight: bold;margin-left: 10rpx;color: #FF5310;">断开连接</text>
					</view>
			
					<view class="" style='position:absolute;right:18rpx;top:20rpx;display:flex;font-size:24rpx'>
						<!-- <view class="" @click="addSymptom">
							填写症状
						</view> -->
					<!-- 	<view class="" style="margin-left:50rpx">
							<image src="../../static/images/x.png" mode="" style="width:40rpx;height:40rpx"
								@click='showMoremask=false'></image>
						</view> -->
					</view>
				</view>
				<view class="content" style="height: 500rpx;overflow: auto;width:100%;color:#0052d9">
				   <view class="" style='width:100%;display: flex;margin-top:25px;justify-content: space-between;'>
				   	<view class="" style="width:115px;border-radius: 7rpx;padding:6px 12px;background-color: #19BE6B;color:#fff;margin-left:20px;" @click='noticeData'>
				   		获取广播数据
				   	</view>
					<view class="" style="width:85px;border-radius: 7rpx;padding:6px 12px;background-color: #19BE6B;color:#fff;margin-left:20px;" @click="sameTheTime()"> 
						同步时间
					</view>
				   </view>
				   
				   <view class="" style="border:1px solie #010101; border-radius: 5px;width:100%;margin-top:20px;padding:6px;box-sizing: border-box;">
				   <view class="item" style="width:100%;" v-for="(item,idx) in blueDataArr" :key='idx'>
				   	{{item}}
				   </view>
				   </view>
				</view>
			</view>
		<!-- 头部 -->
		<view class="navbar">
			<u-icon @click="navigateBack" class="icon-left" name="arrow-left" color="#000" size="50"></u-icon>
			<text>蓝牙设备</text>
		</view>
		<view class="content">
			<view class="" @click="initBlue()" style="width:85px;border-radius: 7rpx;padding:6px 12px;background-color: #19BE6B;color:#fff;margin-left:20px;">
				搜索蓝牙
			</view>
			<view class="title" style="margin-top:12px;margin-left:20px;" v-if='list.length' >
				已发现以下设备：
			</view>
			<view class="list-content">
				<view class="list" v-for='(item,idx) in list' :key='idx' @click='connect(item)'>
					<view class="name">
						{{item.name}}
					</view>
					<view class="deviceid">
						{{item.deviceId}}
					</view>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	var CRC = {};
	
	CRC._auchCRCHi = [
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
	  0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
	  0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
	  0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
	  0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
	  0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
	  0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
	  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
	  0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
	  0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
	  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
	  0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
	  0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
	];
	CRC._auchCRCLo = [
	  0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
	  0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
	  0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
	  0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
	  0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
	  0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
	  0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
	  0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
	  0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
	  0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
	  0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
	  0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
	  0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
	  0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
	  0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
	  0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
	  0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
	  0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
	  0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
	  0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
	  0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
	  0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
	  0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
	  0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
	  0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
	  0x43, 0x83, 0x41, 0x81, 0x80, 0x40
	];
	
	CRC.CRC16 = function (buffer) {
	  var hi = 0xff;
	  var lo = 0xff;
	  for (var i = 0; i < buffer.length; i++) {
	    var idx = hi ^ buffer[i];
	    hi = (lo ^ CRC._auchCRCHi[idx]);
	    lo = CRC._auchCRCLo[idx];
	  }
	  return CRC.padLeft((hi << 8 | lo).toString(16).toUpperCase(), 4, '0');
	};
	
	CRC.isArray = function (arr) {
	  return Object.prototype.toString.call(arr) === '[object Array]';
	};
	
	CRC.ToCRC16 = function (str) {
	  return CRC.CRC16(CRC.isArray(str) ? str : CRC.strToByte(str));
	};
	
	CRC.ToModbusCRC16 = function (str) {
	  return CRC.CRC16(CRC.isArray(str) ? str : CRC.strToHex(str));
	};
	
	CRC.strToByte = function (str) {
	  var tmp = str.split(''), arr = [];
	  for (var i = 0, c = tmp.length; i < c; i++) {
	    var j = encodeURI(tmp[i]);
	    if (j.length == 1) {
	      arr.push(j.charCodeAt());
	    } else {
	      var b = j.split('%');
	      for (var m = 1; m < b.length; m++) {
	        arr.push(parseInt('0x' + b[m]));
	      }
	    }
	  }
	  return arr;
	};
	
	CRC.convertChinese = function (str) {
	  var tmp = str.split(''), arr = [];
	  for (var i = 0, c = tmp.length; i < c; i++) {
	    var s = tmp[i].charCodeAt();
	    if (s <= 0 || s >= 127) {
	      arr.push(s.toString(16));
	    }
	    else {
	      arr.push(tmp[i]);
	    }
	  }
	  return arr;
	};
	
	CRC.filterChinese = function (str) {
	  var tmp = str.split(''), arr = [];
	  for (var i = 0, c = tmp.length; i < c; i++) {
	    var s = tmp[i].charCodeAt();
	    if (s > 0 && s < 127) {
	      arr.push(tmp[i]);
	    }
	  }
	  return arr;
	};
	
	CRC.strToHex = function (hex, isFilterChinese) {
	  hex = isFilterChinese ? CRC.filterChinese(hex).join('') : CRC.convertChinese(hex).join('');
	
	  //清除所有空格
	  hex = hex.replace(/\s/g, "");
	  //若字符个数为奇数，补一个空格
	  hex += hex.length % 2 != 0 ? " " : "";
	
	  var c = hex.length / 2, arr = [];
	  for (var i = 0; i < c; i++) {
	    arr.push(parseInt(hex.substr(i * 2, 2), 16));
	  }
	  return arr;
	};
	
	CRC.padLeft = function (s, w, pc) {
	  if (pc == undefined) {
	    pc = '0';
	  }
	  for (var i = 0, c = w - s.length; i < c; i++) {
	    s = pc + s;
	  }
	  return s;
	};
	export default {
		data() {
			return {
				lyid:'',
				showMask:false,
				list: [],
				deviceId: '',
				servicesId: '',
				notifyId: '',
				writeId: '',
				balanceData: '',
				hexstr: '',
				readId: '',
				deviceInfo: [],
				data: [],
				blueDataArr:[],
				value:''
			}
		},
		mounted() {
			console.log(CRC.ToModbusCRC16('0181170720215920006000FA00FA203001', true))
			// this.initBlue()
			this.$api.getDeviceList().then(res => {
				let list = []
				if (res.code === 200) {
					list = res.result.list
					list.forEach(ele => {
						if (ele.deviceStatus === 'Y') {
							this.deviceInfo = ele
							// this.uploadData()
						}
					})
				}
			})
		},
		methods: {
			back(){
					this.list = []
					this.showMask = false
					this.closeBlue()
			},
			today() {
				var myDate = new Date();
				var year = myDate.getFullYear(); //获取当前年
				var mon = myDate.getMonth() + 1; //获取当前月
				if (mon < 10) {
					mon = "0" + mon;
				}
				var date = myDate.getDate(); //获取当前日
				if (date < 10) {
					date = "0" + date;
				}
				var hours = myDate.getHours(); //获取当前小时
				if (hours < 10) {
					hours = "0" + hours;
				}
				var minutes = myDate.getMinutes(); //获取当前分钟
				if (minutes < 10) {
					minutes = "0" + minutes;
				}
				var seconds = myDate.getSeconds(); //获取当前秒
				if (seconds < 10) {
					seconds = "0" + seconds;
				}
				let dates = year + "-" + mon + "-"
				return dates
			
			},
			getTimer(){
				var myDate = new Date();
				var mon = myDate.getMonth() + 1; //获取当前月
				if (mon < 10) {
					mon = "0" + mon;
				}
				var date = myDate.getDate(); //获取当前日
				if (date < 10) {
					date = "0" + date;
				}
				var hours = myDate.getHours(); //获取当前小时
				if (hours < 10) {
					hours = "0" + hours;
				}
		
				var minutes = myDate.getMinutes(); //获取当前分钟
				if (minutes < 10) {
					minutes = "0" + minutes;
				}
				var seconds = myDate.getSeconds(); //获取当前秒
				if (seconds < 10) {
					seconds = "0" + seconds;
				}
				
				let timer = this.timerToHex(mon)+this.timerToHex(date)+this.timerToHex(hours)+this.timerToHex(minutes)
				return timer
			},
			timerToHex(timer) {
			
				const result =String(timer.toString(16))
				
				if (result.length> 1) {
					return result
				} else {
					return '0' + result
				}
			
			},
			stampToDate(stamp){
				    // 时间戳 
				  
				    // 此处时间戳以毫秒为单位
				    let date = new Date(parseInt(stamp));
				    let Year = date.getFullYear();
				    let Moth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
				    let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
				    let Hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
				    let Minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
				    let Sechond = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
				    let  GMT =  Year + '-' + Moth + '-' + Day + '   '+ Hour +':'+ Minute  + ':' + Sechond;
				    
				   return GMT // 2022-09-07 15:56:07
			},
			uploadData() {
				const day = this.today().substring(8,10)
				if(this.data.length&&day!=24){
					this.data.forEach((ele,i)=>{
					const date = new Date()
					const now = Date.parse(date)
					const timer = now-(this.data.length-i)*60000
					ele.timer = this.stampToDate(timer)	
					})
				}
				const params = {
					deviceid: this.deviceInfo.device_code,
					devices: this.data,
					lyid:this.lyid

				}
				this.$api.uploadBlueToothData(params).then(res => {
					if (res.code === 200) {
						console.log('111')
						this.data = []
					} else {
						console.log(res, 222)
					}
				})
			},
			navigateBack() {
				uni.navigateTo({
					url: '/pages/index/index'
				})
				
			},
			/**获取已授权列表*/
			getUserSetting() {
				console.log("获取已授权列表")
				var that = this;
				wx.getSetting({
					success(res) {
						var authSetting = res.authSetting
						console.log(res.authSetting)
						if (!res.authSetting['scope.bluetooth']) {
							//授权获取蓝牙权限
							wx.authorize({
								scope: 'scope.bluetooth',
								success() {
									console.log("成功获取蓝牙权限")
									that.initBlue()
								},
								fail() {
									console.log("蓝牙权限获取失败")
								}
							})
						} else {
							that.initBlue()
						}
					},
					fail(f) {
						console.log(f)
					}
				})
			},

			/**初始化蓝牙设备*/
			initBlue() {
				console.log("初始化蓝牙")
				var that = this;
				wx.openBluetoothAdapter({
					success: function(res) {
						that.findBlue()
					},
					fail: function(res) {
						uni.showModal({
							title: '蓝牙提示',
							content: '未开启蓝牙，请开启！'
						});
						console.log("e", "请开启蓝牙定位")
					}
				})
			},

			/**开始搜索蓝牙设备*/
			findBlue() {
				var that = this
				wx.startBluetoothDevicesDiscovery({
					services: [],
					allowDuplicatesKey: true,
					interval: 0,
					powerLevel: 'high',
					success: function(res) {
						console.log("开始搜索蓝牙设备", res)
						//加个延时，避免获取数据为空
						setTimeout(() => {
							that.getBlue()
						}, 300)
					}
				})
			},
			inArray(arr, key, val) {
				for (let i = 0; i < arr.length; i++) {
					if (arr[i][key] === val) {
						return i;
					}
				}
				return -1;
			},
			closeBlue() {
				let that = this
				wx.closeBluetoothAdapter({
					success:(res)=>{
						console.log('关闭适配器成功！')
						
					},
					fail:(res)=>{
						console.log('关闭适配器失败！',res)
					}
				})
				wx.closeBLEConnection({
					deviceId:this.deviceId,
					success:(res)=>{
						console.log(res,'关闭蓝牙成功!')
						
					},
					fail:(res)=>{
						console.log('关闭蓝牙失败！',res,this.deviceId)
					}
				})
			},

			/**获取搜索到的设备信息*/
			getBlue() {
				var that = this
				//        wx.getBluetoothDevices({
				//            success: function (res) {
				// console.log(res,111)
				//                var blueToothList = []
				// that.list = res.devices
				//                for (var i = 0; i < res.devices.length; i++) {
				//                    if (res.devices[i].name != "未知设备") {
				//                        console.log("遍历已知蓝牙设备" + i, res.devices[i].deviceId, res.devices[i].name, res.devices[i].RSSI)
				//                    }
				//                }
				//            },
				//            fail: function () {
				//                console.log("搜索蓝牙设备失败")
				//            }
				//        })

				wx.onBluetoothDeviceFound(res => {
					res.devices.forEach(device => {
						if (!device.name && !device.localName) {
							return
						}
						const foundDevices = that.list
						const idx = that.inArray(foundDevices, 'deviceId', device.deviceId);
						let str = ''
						if(device.name){
							str = device.name.substring(0,3)
						}else{
							str = device.localName.substring(0,3)
						}
					
						console.log(str,777)
						if(str==='ZLN'){
							// that.connect(device)
							
						}
						if (idx === -1) {
							that.list.push(device)
							
						}


					})
					console.log(res, 444)

				})
			},
			connect(item) {
				this.lyid = item.name
				this.deviceId = item.deviceId
				this.connetBlue()
			},
			/**获取到设备之后连接蓝牙设备*/
			connetBlue() {
				this.blueDataArr = []
				this.showMask = true
				setTimeout(() => {
					//getBlue里面获取的deviceId
					var deviceId = this.deviceId
					var that = this;
					wx.createBLEConnection({
						deviceId: deviceId, //设备id
						success: function(res) {
							console.log("连接蓝牙成功!")
							wx.stopBluetoothDevicesDiscovery({
								success: function() {
									console.log('连接蓝牙成功之后关闭蓝牙搜索,避免耗电');
								}
							})
							//获取蓝牙服务ID
							that.getServiceId()
							//连接成功，开始监听蓝牙连接状态，断开后重连
							that.onStateChange()
						},
						fail: function(f) {
							console.log(f, 555)
						}
					})
				}, 200)
			},

			/**开始监听蓝牙连接状态*/
			onStateChange() {
				wx.onBLEConnectionStateChange(this.stateChangeFun)
			},

			/**蓝牙状态监听方法*/
			stateChangeFun(res) {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				var connectStatus = res.connected
				if (connectStatus == false) {
					console.log('蓝牙断开重连', `device ${res.deviceId} state has changed, connected: ${res.connected}`)
					this.reconnectBlue()
				}
			},

			/**蓝牙重连*/
			reconnectBlue() {
				var deviceId = this.deviceId
				var that = this;
				wx.createBLEConnection({
					deviceId: deviceId,
					success() {
						console.log("蓝牙重连成功！")
						 that.getServiceId()
							
					},
					fail() {
						that.reconnectBlue()
					}
				})
			},

			/**蓝牙设备的服务uuid*/
			getServiceId() {
				var that = this
				wx.getBLEDeviceServices({
					deviceId: that.deviceId,
					success: function(res) {
						console.log("蓝牙服务信息", res)
						//[0]这个服务ID下面的特征值ID有notify和write为true的，每个设备不一样，根据你的设备来，可能是[0]也可能是[1]或者其他的
						var model = res.services[0]

						that.servicesId = model.uuid

						that.getCharacteId()
					}
				})
			},

			/**查看蓝牙特征值*/
			getCharacteId() {
				var that = this
				wx.getBLEDeviceCharacteristics({
					deviceId: that.deviceId,
					serviceId: that.servicesId,
					success: function(res) {
						console.log("蓝牙特征值", res)
						var model = ""
						for (var i = 0; i < res.characteristics.length; i++) {
							model = res.characteristics[i]
							//接收蓝牙发送过来的数据需要这个uuid
							if (model.properties.notify == true) {

								that.notifyId = model.uuid

							}
							if (model.properties.read == true) {

								that.readId = model.uuid

							}
							//给蓝牙发送数据需要这个uuid
							if (model.properties.write == true) {

								that.writeId = model.uuid
							}
						}
						 that.startNotice(that.notifyId)
					}
				})
			},
			noticeData(){
				this.startNotice(this.notifyId)
			},
			/**监听蓝牙数据*/
			startNotice(uuid) {
				var that = this;
				wx.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: that.deviceId,
					serviceId: that.servicesId,
					characteristicId: uuid,
					success: function(res) {
						console.log("监听成功！ " + JSON.stringify(res))
						 that.readData()
						// console.log('1117'+that.getTimer()+'003C017C02BC01022AEE',111)
						 //that.sendOrder('0117'+that.getTimer()+'003C017C02BC01022AEE')
						 that.sendOrder('028280B1')
						// that.onBLECharacteristicValueChange()
						// setTimeout(()=>{
						// that.sendOrder('0x11')
						// },1000)
					

					},
					fail: function(fail) {
						console.log("蓝牙监听失败！")
					}
				})
			},
			onBLECharacteristicValueChange() {
				console.log(555)
				let that = this
				wx.onBLECharacteristicValueChange(res => {
					console.log(res, 111, JSON.stringify(res))
					let hex = Array.prototype.map.call(new Uint8Array(res.value), x => ('00' + x.toString(16))
						.slice(-2)).join('')
					console.log(hex, 999)
					console.log('监听低功耗蓝牙设备特征值变化事件成功')
					that.balanceData = that.buf2string(res.value)
					// console.log(this.balanceData,333)
					that.hexstr = that.receiveData(res.value)
					// console.log(that.hexstr,777)

				})
			},
			
			sameTheTime(){
				const timer = this.getTimer()
				
				const crcData = '018117'+timer+'00006000fa00fa203001' + CRC.ToModbusCRC16('018117'+timer+'00006000fa00fa203001', true)
				
				console.log('发送同步时间指令',crcData,CRC.ToModbusCRC16('018117'+timer+'00006000fa00fa203001', true))
			
				 this.sendOrder(crcData)
				// this.sendOrder('0181170720215920006000fa00fa2030010B52')
			},
			oneMorePost(){
				setTimeout(()=>{
					console.log('重新连接')
					this.noticeData()
				},1000*60)
			},
			readData() {
				let that = this
				wx.onBLECharacteristicValueChange(res => {
					// console.log(that.buf2string(res.value), '16进制解析')
					// let hex = Array.prototype.map.call(new Uint8Array(res.value), x => ('00' + x.toString(16)).slice(-2)).join('')
					let hex = that.ab2hex(res.value)
					console.log(hex,676)
					if(String(hex).length<12){
						console.log('无数据，等待再一次查询')
						// that.closeBlue()
						that.oneMorePost()
						return
					}
					this.blueDataArr.push(hex)
					const num = hex.length/32
					const arr = []
					for(let i = 0;i<num;i++){
						 arr.push(hex.substring(i*32,(i+1)*32))
					}
					
					console.log(hex,88778,arr)
					if(arr.length){
						arr.forEach(ele=>{
							that.decodeHex(ele)
						})
					}
					// that.sendOrder('028280B1')
					if(that.data.length && arr.length<15){
						 that.uploadData()
						 // that.closeBlue()
							// that.noticeData()
						 // that.oneMorePost()
					}
					if(arr.length===1){
						that.oneMorePost()
					}else{
						that.noticeData()
					}
					// that.decodeHex(hex)
					// that.balanceData += that.buf2string(res.value)
					// console.log(this.balanceData,333)
					// that.hexstr = that.hexCharCodeToStr(hex)
					// console.log(that.hexstr,777)

				})
				wx.readBLECharacteristicValue({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.servicesId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.readId,
					success: function(res) {
						console.log('readBLECharacteristicValue:', res) // ok
					}
				})

			},
			decodeHex(str) {
						// const timer =
						// 	`${this.today()} ${this.parseTimer(str.substring(8,10))}:${this.parseTimer(str.substring(10,12))}:${this.parseTimer(str.substring(12,14))}`
						// const power = parseInt(str.substring(14, 16), 16)
						// const temp = parseInt(str.substring(16, 20), 16) / 10
						// const humidity = parseInt(str.substring(20, 24), 16) / 10
						// const xData = parseInt(str.substring(24, 28), 16)
						// const yData = parseInt(str.substring(28, 32), 16)
						// const zData = parseInt(str.substring(32, 36), 16)
						// const crcData = parseInt(str.substring(36, 38), 16)
						const timer =
							`${this.today()}${this.parseTimer(str.substring(6,8))} ${this.parseTimer(str.substring(8,10))}:${this.parseTimer(str.substring(10,12))}:${this.parseTimer(str.substring(12,14))}`
						const power = parseInt(str.substring(14, 16), 16)
						const temp = parseInt(str.substring(16, 20), 16) / 10
						const humidity = parseInt(str.substring(20, 24), 16) / 10
						const xData = parseInt(str.substring(24, 28), 16)
						// const yData = parseInt(str.substring(28, 32), 16)
						// const zData = parseInt(str.substring(32, 36), 16)
						const crcData = parseInt(str.substring(28, 32), 16)
						const zData = 	parseInt(str.substring(0, 4), 16)
							
						// if (!this.data.length ) {
					
							
							// wx.closeBLEConnection({
							// 	deviceId::this.deviceId,
							// 	success: function(res) {
							// 		console.log('断开蓝牙设备成功',res)
							// 	},
							// 	fail:function(res){
							// 		console.log(res)
							// 	}
							// })
							// wx.closeBluetoothAdapter({
							// 	success: function(res) {
							// 		console.log('断开成功',res)
							// 	}
							// })
						// } else {
							var date = new Date()
							const timeStamp = Date.parse(timer)
							const now = Date.parse(date)
							// if(now<timeStamp){
							// 	return
							// }
							if(timer.substring(8,10)==24){
								this.sameTheTime()
							}
							if(temp>42||temp<10||humidity>99||humidity<1){
								return
							}
							this.data.push({
								timer: timer,
								power: power,
								temp1: temp,
								humidity: humidity,
								xdata: xData,
								 ydata: 0,
								 zdata:zData,
								crcData: crcData
							})
							// this.uploadData()
							console.log(this.data.length)
						// }
		
					},
			parseTimer(timer) {

				const result = parseInt(timer, 16)
				console.log(timer,11,result,22)
				if (result> 9) {
					return result
				} else {
					return '0' + result
				}

			},
			/**发送数据*/
			sendOrder(write) {
				 let buffer = this.string2buffer(write);
				 
				   var typedArray = new Uint8Array(write.match(/[\da-f]{2}/gi).map(function (h) {
				      return parseInt(h, 16)
				    }))
				let pos = 0;
				let bytes = buffer.byteLength;
				var that = this

				//因为微信小程序使用蓝牙发送数据限制20字节内的原因，需要对超过20字节的数据拆包进行发送
				while (bytes > 0) {
					let tmpBuffer;
					if (bytes > 20) {
						tmpBuffer = buffer.slice(pos, pos + 20);
						pos += 20;
						bytes -= 20;
					} else {
						tmpBuffer = buffer.slice(pos, pos + bytes);
						pos += bytes;
						bytes -= bytes;
					}
					console.log(tmpBuffer, 'tmpBuffer',typedArray.buffer)
					wx.writeBLECharacteristicValue({
						deviceId: that.deviceId,
						serviceId: that.servicesId,
						characteristicId: that.writeId,
						value: typedArray.buffer,
						success: (res) => {
							console.log("写入成功", res)
							// that.onBLECharacteristicValueChange()
							  that.readData()
						},
						fail: (f) => {
							console.log("写入失败")
						}
					})
				}
			},
			buf2string(buffer) {
				var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
				return arr
					.map((char, i) => {
						return String.fromCharCode(char)
					})
					.join('')
			},
			receiveData(buf) {
				return this.hexCharCodeToStr(this.ab2hex(buf))
			},


			/**将16进制转化为ArrayBuffer*/
			string2buffer(str) {
				return new Uint8Array(str.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				})).buffer
			},

			hexCharCodeToStr(hexCharCodeStr) {
				var trimedStr = hexCharCodeStr.trim()
				var rawStr =
					trimedStr.substr(0, 2).toLowerCase() === '0x' ?
					trimedStr.substr(2) :
					trimedStr
				var len = rawStr.length
				var curCharCode
				var resultStr = []
				for (var i = 0; i < len; i = i + 2) {
					curCharCode = parseInt(rawStr.substr(i, 2), 16)
					resultStr.push(String.fromCharCode(curCharCode))
				}
				return resultStr.join('')
			},


			/**将ArrayBuffer转换成字符串*/
			ab2hex(buffer) {
				var hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('');
			},

		},

		/**生命周期函数--监听页面加载*/
		onLoad(options) {
			// wx.onBLECharacteristicValueChange(function(res) {
			// 	// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据，所以需要通过一个方法转换成字符串
			// 	var data = this.ab2hex(res.value)
			// 	//下面写你接收到数据之后的业务逻辑代码
			// })
		},

		/**生命周期函数--监听页面隐藏*/
		onUnload() {
			//关闭蓝牙连接状态监听、蓝牙连接，避免耗电
			// this.offStateChange()
			this.closeBlue()
		}

	}
</script>

<style scoped lang='scss'>
	.mask {
		position: fixed;
		z-index: 166;
		margin: 15rpx 15rpx;
		padding: 15rpx 30rpx;
		box-sizing: border-box;
		bottom: 70rpx;
		background: #F6F7FB;
		border-radius: 6rpx;
		height: 84vh;
		width: 720rpx;
	}
	.container {
		width: 100%;

		.navbar {
			padding-top: 90rpx;
			padding-bottom: 40rpx;
			width: 750rpx;
			color: #000;
			background-color: #fff;
		}

		.navbar {
			padding-top: 90rpx;
			padding-bottom: 40rpx;
			width: 750rpx;
			color: #000;
			background-color: #fff;
		}

		.navbar>text {
			font-size: 36rpx;
			padding-left: 200rpx;
			font-weight: bold;
		}

		.content {
			width: 100%;

			.list-content {
				width: 100%;
				padding: 10rpx 15rpx;
				box-sizing: border-box;

				.list {
					width: 100%;
					padding: 12px;
					box-sizing: border-box;
					border-radius: 3px;
					border: 1px solid #f1f1f1;
					heigth: 120rpx;
					margin-top: 12px;
				}
			}
		}
	}
</style>